package com.itouch.bracelet.activity;

import java.text.DecimalFormat;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.MedAndLacPercentResult;
import com.itouch.bracelet.bean.MedPercentAndSport;
import com.itouch.bracelet.bean.MedPercentAndSportResult;
import com.itouch.bracelet.bluetooth.BluetoothConstants;
import com.itouch.bracelet.bluetooth.BluetoothHandler;
import com.itouch.bracelet.bluetooth.BluetoothPacket;
import com.itouch.bracelet.bluetooth.BluetoothService;
import com.itouch.bracelet.bluetooth.BluetoothType;
import com.itouch.bracelet.bluetooth.BluetoothUtil;
import com.itouch.bracelet.bluetooth.BluetoothValue;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.widget.holographlibrary.Line;
import com.itouch.widget.holographlibrary.LineGraph;
import com.itouch.widget.holographlibrary.LinePoint;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

/**
 * 设备
 * authored by sunshineHu，hahahahahahaha
 * copyright essence
 * fool's Day 2015
 * God like change
 * oh yeah
 * 
 */
public class MainDeviceActivity extends BaseActivity implements OnClickListener,DialogInterface.OnClickListener{

	private static final String LOG_TAG = "MainDeviceActivity";

	private TextView m_step;
	private LineGraph li;
	private TextView c_tem;

	private ImageView avat_change;
	private ImageView avat_main;
	private TextView child_name;
	private TextView child_device;
	
	private TextView m_calorie;
	private TextView m_m;

	private LinearLayout templl;
	

	private LinearLayout childtemp;
	private LinearLayout childstep;
	
	private TextView c_step;
	
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	
	private double[] temperature;
	
	private Child currentChild;//当前孩子
	
	@Override
	protected int setContentViewById() {
		return R.layout.activity_main_device;
	}

	
	
	
	@Override
	protected void initViews() {
		
		/**
		 * 判断是否连接设备
		 */
		if(!BluetoothValue.INSTANCE.isBluetoothStatus()){
			
			AlertDialog.Builder builer = new Builder(this);
			builer.setTitle("设备连接");
			builer.setMessage("您尚未连接小爱手环，点击确定开始连接!");
			// 当点确定按钮时从服务器上下载 新的apk 然后安装
			builer.setPositiveButton("确定", this);
			builer.setNegativeButton("取消", null);

			AlertDialog dialog = builer.create();
			dialog.show();
			
		}
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothHandler.ACTION_STATUS);
		filter.addAction(BluetoothHandler.ACTION_DATA);
		registerReceiver(receiver, filter);
		
		
		m_m = (TextView) findViewById(R.id.m_m);
		m_calorie = (TextView) findViewById(R.id.m_calorie);
		
		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.c_default_avatar)
		.showImageOnFail(R.drawable.c_default_avatar)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300)).build();
		
		m_step = (TextView) findViewById(R.id.m_step);
		c_tem = (TextView) findViewById(R.id.c_tem);
		li = (LineGraph) findViewById(R.id.linegraph);

		avat_change = (ImageView) findViewById(R.id.avat_change);
		avat_change.setOnClickListener(this);

		avat_main = (ImageView) findViewById(R.id.avat_main);
		avat_main.setOnClickListener(this);
		child_name = (TextView) findViewById(R.id.child_name);
		child_device = (TextView) findViewById(R.id.child_device);
		
		templl=(LinearLayout) findViewById(R.id.templl);
	
		
		//体温和计步器，根据市儿童还是婴儿择一显示
		childtemp=(LinearLayout) findViewById(R.id.child_temp);
		childstep=(LinearLayout) findViewById(R.id.child_step);

		c_step = (TextView) findViewById(R.id.c_step);
		
		
	}

	@Override
	protected void initData() {
	
		getStepData(UserCache.getOauth(this).getUserId(),true);
		//changeChildAvatar(false);
		
		//加载孩子
		if(UserCache.getOauth(this).getChildlist()!=null&&UserCache.getOauth(this).getChildlist().size()>0){
			int position=UserCache.getOauth(this).childPosition;//当前选中孩子
			Child child = UserCache.getOauth(this).getChildlist().get(position);
			child_name.setText(child.getName());
			child_device.setText(child.getDeviceNo());
			imageLoader.displayImage(child.getPath(), avat_main, options);
			
			//根据孩子类型显示视图
			if(child.getCustomerFlag()==1){
				childtemp.setVisibility(View.VISIBLE);
				childstep.setVisibility(View.INVISIBLE);
				//体温
				getTempData(child.getId());
			}else if(child.getCustomerFlag()==2){
				childstep.setVisibility(View.VISIBLE);
				childtemp.setVisibility(View.INVISIBLE);
				//计步器
				getStepData(child.getId(),false);
			}
			
		}else{
			//当前账户没有孩子
			templl.setVisibility(View.INVISIBLE);
			
		}
	}
	

	/**
	 * 获取计步器数据
	 * flag true 母亲  false 儿童
	 * @param customerId
	 */
	private void getStepData(String customerId,final boolean flag) {

		Uri.Builder builder = Uri.parse(Constants.GET_MED_SPORT).buildUpon();
		builder.appendQueryParameter("customerId", customerId + "");

		RequestQueue requestQueue = Volley.newRequestQueue(this);
		Log.d("GET_MED_SPORT", "GET_MED_SPORT" + builder.toString());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.GET, builder.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						Log.d("GET_MED_SPORT",
								"GET_MED_SPORT" + arg0.toString());
						try {
							MedPercentAndSportResult a = new Gson().fromJson(
									arg0.toString(),
									MedPercentAndSportResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {

								MedPercentAndSport result = a.getRows();
								
								//setMotherInfo(result);
								//设置步数
								String step=result.getSteps();
								
								if(flag){
									
									
									if(step!=null&&step.length()>0){
									m_step.setText(step);
									}
									
									String cal=result.getCalorie();
									if(cal!=null&&cal.length()>0){
										m_calorie.setText(getString(R.string.cal_hint1)+result.getCalorie()+getString(R.string.cal_hint2));
									}
									//设置步行的公里数
									String mil=result.getMileage();
									if(mil!=null&&mil.length()>0){
										m_m.setText(getString(R.string.step_hint1)+mil+getString(R.string.step_hint2));
									}
									
								}else{
									
									c_step.setText(step);
									
								}
								
							} else {
								Toast.makeText(MainDeviceActivity.this, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						
						Toast.makeText(MainDeviceActivity.this,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(jsonObjectRequest);
	}

	/**
	 * 获取体温数据
	 * @param customerId
	 * @param change
	 */
	private void getTempData(String customerId) {
		Uri.Builder builder = Uri.parse(Constants.GET_MED_LAC).buildUpon();
		builder.appendQueryParameter("customerId", customerId + "");

		RequestQueue requestQueue = Volley.newRequestQueue(MainDeviceActivity.this);
		Log.d("GET_MED_LAC", "GET_MED_LAC" + builder.toString());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.GET, builder.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						try {
							MedAndLacPercentResult a = new Gson().fromJson(
									arg0.toString(),
									MedAndLacPercentResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								//setChildDataInfo(a.getRows());
								// 设置体温
								temperature=a.getRows().getTemperature();
								setLine(temperature);

							} else {
								Toast.makeText(MainDeviceActivity.this, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						Toast.makeText(MainDeviceActivity.this,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(jsonObjectRequest);
	}
	
	private void setLine(double[] temperature) {
		if (li != null) {
			li.removeAllLines();
		}

		if (temperature == null || temperature.length < 1) {
			//没有提问数据，就默认为5个0 
			temperature = new double[5];
		}
		int size = temperature.length;

		Line l = new Line();

		try {
			// 设置最上面的文字温度
			DecimalFormat df=df = new DecimalFormat("##.#");
			c_tem.setText(df.format(temperature[0]) + "℃");

			if (size == 1) {
				// 如果返回的体温数据只有一条，重复显示5次
				double t = temperature[0];
				for (int i = 0; i < 5; i++) {
					LinePoint p = new LinePoint();
					p.setX(i);
					p.setY((int)t);
					p.setLabel_string(df.format(t));
					l.addPoint(p);
				}

			} else {
				// 如果返回的体温数据大于5条，只显示最新的5条
				size = size > 5 ? 5 : size;
				for (int i = 0; i < size; i++) {
					double t = temperature[i];
					LinePoint p = new LinePoint();
					p.setX(i);
					p.setY((int)t);
					p.setLabel_string(df.format(t));
					l.addPoint(p);
				}
			}

			l.setColor(getResources().getColor(R.color.comm_pink));
			li.addLine(l);
			li.setLabelSize(20);
			li.setRangeY(0, 40);
			li.setLineToFill(0);

		} catch (NumberFormatException n) {

		}

	}
	

	public void back(View v){
		finish();
	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.avat_main:
			// 小孩子主头像的点击事件
			break;

		default:

			break;

		}

	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		if (adapter == null) {
			Toast.makeText(this, "该设备不支持蓝牙！", Toast.LENGTH_SHORT)
					.show();
		} else {
			
			String[] devices=UserCache.getOauth(this).getDeviceNo().split(":");
			if(devices.length!=6){
				Toast.makeText(this, "设备号错误，请修改后重试！", Toast.LENGTH_SHORT)
				.show();
				return;
			}else{
				
				int part1=Integer.valueOf(devices[4], 16);
				int part2=Integer.valueOf(devices[5], 16);
				byte[] ids={(byte)part1,(byte)part2};
				BluetoothValue.INSTANCE.id=ids;
			}
			
			if (adapter.enable()) {
				// open
				
				BluetoothValue.INSTANCE.setBluetoothStatus(true);
				
				Intent in = new Intent(this,
						BluetoothService.class);
				in.putExtra("address", UserCache.getOauth(MainDeviceActivity.this).getDeviceNo());
				startService(in);
			} else {
				Toast.makeText(this, "蓝牙尚未打开，请打开后重试！",
						Toast.LENGTH_SHORT).show();
				Intent enabler = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivity(enabler);
			}
		}
	}
	
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);// 销毁
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(BluetoothHandler.ACTION_STATUS)){
				int status = intent.getIntExtra("status", -1);
				if (status == BluetoothConstants.MESSAGE_CONNECT_SUCCESS) {
					Toast.makeText(MainDeviceActivity.this, "连接成功！", Toast.LENGTH_SHORT)
							.show();
				} else if (status == BluetoothConstants.MESSAGE_CONNECT_FAILED) {
					String error=intent.getStringExtra("error");
					Toast.makeText(MainDeviceActivity.this, "连接失败！", Toast.LENGTH_SHORT)
					.show();
					
				}
			}else if(intent.getAction().equals(BluetoothHandler.ACTION_DATA)){
				
				BluetoothPacket packet=(BluetoothPacket) intent.getSerializableExtra("packet");
				if(packet.getType()==BluetoothType.DATA_STEP_MOTHER){
					
					final int steps=BluetoothUtil.getSteps(packet);
					m_step.setText(steps+"");
				
				}else if(packet.getType()==BluetoothType.DATA_STEP_CHILD){
					LoginUser user=UserCache.getOauth(MainDeviceActivity.this);
					if(user.getChildlist().size()>0){
						//校验是当前孩子
						Child child=user.getChildlist().get(user.childPosition);
						if(BluetoothUtil.verifyChild(child, packet.getId())){
							final int steps=BluetoothUtil.getSteps(packet);
							c_step.setText(steps+"");
						}
					}
				}else if(packet.getType()==BluetoothType.DATA_TEMPERATURE){
					//这个比较麻烦。。
					LoginUser user=UserCache.getOauth(MainDeviceActivity.this);
					if(user.getChildlist().size()>0){
						Child child=user.getChildlist().get(user.childPosition);
						//if(child.getDeviceNo().equals(other))
						String deviceNo=child.getDeviceNo();
						if(deviceNo!=null&&deviceNo.length()==5&&deviceNo.contains(":")){
							String[] devcode=deviceNo.split(":");
							int part1=Integer.valueOf(devcode[0],16);
							int part2=Integer.valueOf(devcode[1],16);
							if(packet.getData()[0]==(byte)part1&&packet.getData()[1]==(byte)part2){
								//孩子匹配成功
								
								if(temperature!=null){
									double[] newarray=new double[temperature.length+1];
									System.arraycopy(temperature, 0, newarray, 1, temperature.length);
									int temp=((packet.getData()[4] & 0xFF) <<8) | (packet.getData()[5] & 0xFF);//byte转int
									newarray[0]=temp/10;
									temperature=newarray;
									setLine(temperature);
								}
							}
							
						}
					}
				}
				
			}
		}
	};

	
	
}